﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XSTDZ.ERP.Application.DataContracts;
using XSTDZ.ERP.Application;
using XSTDZ.ERP.Infrastructure;
using XSTDZ.ERP.WebApp.Models;
using XSTDZ.ERP.Core.Extentions;
using XSTDZ.ERP.WebApp.Models.Ado;
using XSTDZ.ERP.Infrastructure.Authentication;

namespace XSTDZ.ERP.WebApp.Controllers
{
    //销售退货
    public class ProductReturnController : Controller
    {
        private readonly IProductReturnBillService operationServiceImpl = ServiceLocator.Instance.GetService<IProductReturnBillService>();	
        public ActionResult Index()
        {
            ViewBag.orgCode = SystemConfig.ChengDuCode;
            return View();
        }
        #region 查看详细
        [NoAuthorizated("Detail")]
        public ActionResult Detail(Guid id)
        {
            var billModel = operationServiceImpl.GetProductReturnBill(id);
            return View(billModel);
        }
        #endregion
        #region 保存和提交统一入口
        [NoAuthorizated("AddAndConfirm")]
        [HttpPost]
        public ActionResult AddAndConfirm(ProductReturnBillDto roductInBillDto)
        {
            string orgCode = Request.QueryString["orgCode"];
            bool isConfirm = Convert.ToBoolean(Request["isConfirm"]);
            //订单已确认
            if (roductInBillDto.BillState > 0)
            {
                return new EmptyResult();
            }
            //保存(或更新)
            var resultRst = Add(roductInBillDto) as ContentResult;
            string actionResult = resultRst.Content.ToString();
            Guid tempId = Guid.Empty;
            if (Guid.TryParse(actionResult.ToString(), out tempId))
            {
                roductInBillDto.Id = tempId;
            }
            else
            {
                return Content(actionResult.ToString());
            }
            //提交
            if (isConfirm)
            {
               
                if (roductInBillDto.Id != null && !roductInBillDto.Id.Equals(Guid.Empty))//记录已存在
                {
                     ConfirmBill(roductInBillDto.Id);//提交
                     Audit(roductInBillDto.Id, orgCode);//新增：自动审核     2013/11/27去掉审核，做成自动审核）
                  
                }
            }
            return Content("9");
        }
        #endregion
        #region 添加销售退货
        [NoAuthorizated("Add")]
        public ActionResult Add(string orgCode, Guid? id)
        {
            ProductReturnBillDto billModel = null;
            if (id == null || !id.HasValue)
            {
                var NO = new BusinessBillNoCreator().CreateSaleReturnNextNO();

                var initSysData = DataInit.GetOrgAndDefaultWareHourse(orgCode);//初始化默认组织机构和仓库
                var wareHouse = initSysData.Values.FirstOrDefault();

                billModel = new ProductReturnBillDto
                {
                    ReturnBillNo = NO,
                    StorehouseName = wareHouse.StorehouseName,
                    StorehouseID = wareHouse.Id
                };
                ViewBag.BillId = "";
            }
            else
            {
                Guid billId ;
                Guid.TryParse(id.ToString(),out billId);
                billModel = operationServiceImpl.GetProductReturnBill(billId);
               ViewBag.BillId = billId.ToString();
            }
            ViewBag.TempId = Guid.NewGuid();
            ViewBag.orgCode = orgCode;
            billModel.ReturnTime = DateTime.Today;
            return View(billModel);
            
        }
        [HttpPost]
        [NoAuthorizated("Add")]
        public ActionResult Add(ProductReturnBillDto roductInBillDto)
        {
            
            #region 弹出框数据获取
            var model = new ProductCheckBillModel();
            //仓库ID
            var whId=model.GetRequestFormValues(this.HttpContext,"StorehouseName_val");
            if(!Guid.Empty.Equals(whId))
            {
              roductInBillDto.StorehouseID =whId;
            }
            //受理人
            var AcceptId = model.GetRequestFormValues(this.HttpContext, "AcceptName_val");
            if (!Guid.Empty.Equals(AcceptId))
            {
                roductInBillDto.AcceptID = AcceptId;
            }
            //退货客户
            //var ClientId = model.GetRequestFormValues(this.HttpContext, "ClientName_val");
            //if (!Guid.Empty.Equals(ClientId))
            //{
            //    roductInBillDto.ClientID = ClientId;
            //}
            #endregion
            #region 主数据行处理
            roductInBillDto.CreateID = UserModel.GetLoginUserId(this.HttpContext);
	        #endregion
            #region 验证
            if (roductInBillDto.AcceptID == null || roductInBillDto.AcceptID.Equals(Guid.Empty))
            {
                return Content("0");
            }
            if (roductInBillDto.ClientID == null || roductInBillDto.ClientID.Equals(Guid.Empty))
            {
                return Content("0");
            }
            #endregion
            #region 明细行数据处理


            var result = Request.Form["hidProductBillItems"];
            var detailItems = model.ConvertJosnToClass<ProductReturnBillDetailDto>(result);
            if (!string.IsNullOrEmpty(result) && detailItems == null)
            {
                return Content("-1");//明细行异常
            }
            var checkId = Guid.Empty;
            if (roductInBillDto.Id != null && !roductInBillDto.Id.Equals(Guid.Empty))
            {
                checkId = roductInBillDto.Id;
            }
           

	        #endregion
            #region 数据验证
            if (detailItems == null || detailItems.Count <= 0)
            {
                ModelState.AddModelError("", "必须至少存在一个明细行！");
                return Content("-1");
            }
            #endregion
            if (ModelState.IsValid)
            {
                try
                {
                    //验证
                    BLLQuery bq = new BLLQuery();
                    bool isValidate = true;
                    if(detailItems!=null&&detailItems.Count>0)
                    {
                        foreach(var item in detailItems)
                        {
                            if (bq.ValidateOutOfLastSellOutNum(item.StockID, item.GetCount,true))
                            {
                                isValidate= false;
                                break;
                            }
                        }
                    }

                    if (!isValidate) { return Content("-3"); }//验证失败
                    if (roductInBillDto.Id != null && !roductInBillDto.Id.Equals(Guid.Empty))
                    {
                        this.operationServiceImpl.UpdateProductReturnBill(roductInBillDto, detailItems);
                        return Content(roductInBillDto.Id.ToString());
                    }
                    else
                    {
                       var tempId= operationServiceImpl.AddProductReturnBill(roductInBillDto, detailItems);
                       return Content(tempId.ToString());
                    }
                }
                catch (Exception ex)
                {
                    return Content("-2");
                }
               
               // ViewBag.PostState = 9;
                return Content("9");
            }

            return Content("0");
        }
        #endregion
        #region 审核
         [NoAuthorizated("Audit")]
        public ActionResult Audit(Guid billId, string orgCode)
        {
            if(!billId.Equals(Guid.Empty))
            {
                var umodel = new UserModel();
                Guid uid=UserModel.GetLoginUserId(this.HttpContext);
                var initSysData = DataInit.GetOrgAndDefaultWareHourse(orgCode);//初始化默认组织机构和仓库
                this.operationServiceImpl.Audit(new List<Guid>() { billId }, uid , initSysData.Keys.First().Id);
                return Content("9");
            }
            return Content("0");
        }
        #endregion
        #region 提交
         [NoAuthorizated("ConfirmBill")]
         public ActionResult ConfirmBill(Guid billId)
         {
             if (!billId.Equals(Guid.Empty))
             {
                 this.operationServiceImpl.Confirm(billId);
                 return Content("9");
             }
             return Content("0");
         }
         #endregion
        #region 更新至库存
        [NoAuthorizated("UpdateToStock")]
        public ActionResult UpdateToStock(Guid billId, string ids)
        {

            if (ids != "all" && ids.Trim().Length > 0)
            {
                string[] arrayIds = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var guidIds = new List<Guid>();
                arrayIds.Each(id => guidIds.Add(Guid.Parse(id)));
                operationServiceImpl.UpdateToStock(billId, guidIds);
                return Content("9");
            }
            return Content("0");
        }
        #endregion
        #region 删除订单明细（假删除）
         [NoAuthorizated("Delete")]
        public ActionResult Delete(Guid billId,string ids)
        {
            
            if (ids!="all"&&ids.Trim().Length > 0)
            {
                string[] arrayIds = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var guidIds = new List<Guid>();
                arrayIds.Each(id => guidIds.Add(Guid.Parse(id)));
                operationServiceImpl.ConvertProductReturnBillDeleteState(billId, guidIds);
                return Content("9");
            }
            else
            {
                operationServiceImpl.ConvertProductReturnBillDeleteState(billId);
                return Content("9");
            }
            
            return Content("0");
        }
        #endregion
        #region 获取销售退货列表数据
        //暂时获取所有数据
         [NoAuthorizated("GetJsonOfDatas")]
        public ActionResult GetJsonOfDatas()
        {
            #region  EF的查询，效率低下，故暂时放弃不用

            /*
            var productBills = operationServiceImpl.GetProductReturnBills(1, 100);
            if (productBills != null && productBills .Count() != 0)
            {
                var jsonResult = productBills.Select(u =>
                {
                    u.DeleteState = u.Deleted == 0 ? "正常" : "已删除";
                    u.SettleState = u.IsSettle > 0 ? "已结算" : "未结算";
                    //u.CheckStateName = u.CheckState > 0 ? "已审核" : "未审核";
                    return u;
                });
                var target = Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult);
                target = "{\"Rows\":" + target + ",\"Total\":\"" + productBills.Count()+ "\"}";
                return Content(target);
            }
            return Content("");
            */
            #endregion
            return Content(new BLLQuery().GetProductReturnBills(this.HttpContext));
        }
        /// <summary>
        /// 根据销售退货ID，获得销售退货所有明细（不包括删除行）
        /// </summary>
        /// <param name="billId"></param>
        /// <returns></returns>
        [NoAuthorizated("GetJsonOfBillDetails")]
        public ActionResult GetJsonOfBillDetails(Guid billId)
        {
            #region EF的查询，效率低下，故暂时放弃不用
            //var billDetails = operationServiceImpl.GetProductReturnBillDetails(billId).Where(p => p.Deleted == 0).ToList();
            //if (billDetails != null && billDetails.Count() != 0)
            //{
            //    var jsonResult = billDetails.Select(b => { b.DeleteState = b.Deleted == 0 ? "正常" : "已删除"; return b; });
            //    var target = Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult);
            //    target = "{\"Rows\":" + target + ",\"Total\":\"" + billDetails.Count() + "\"}";
            //    return Content(target);
            //}
            // return Content("");
            #endregion
            if (!billId.Equals(Guid.Empty))
            {
                return Content(new BLLQuery().GetProductReturnDetails(billId));

            }
            else
            {
                return Content("");
            }
            
        }
        #endregion
        #region 深圳业务
        public ActionResult SZIndex()
        {
            ViewBag.orgCode = SystemConfig.ShengZhenCode;
            return View("Index");
        }
        #endregion

        #region 打印销售单据
        public ActionResult Print(Guid billId)
        {
            var billAndDetails = operationServiceImpl.GetBillAndDetails(billId); //获得主表数据和从表数据
            var printModel = new  ProductReturnPrint
            {
                  ProductReturnBillDto= billAndDetails.Keys.FirstOrDefault(),
                ProductReturnBillDetailDto = billAndDetails.Values.FirstOrDefault()

            };
            if (printModel.ProductReturnBillDetailDto != null && printModel.ProductReturnBillDetailDto.Count() != 0)
            {
                printModel.ProductReturnBillDto.ReturnMoney=0m;
                foreach (var t in printModel.ProductReturnBillDetailDto)
                {
                    if(t.Deleted!=1){
                        printModel.ProductReturnBillDto.ReturnMoney += Math.Round(((decimal)t.ReturnAmount * t.ReturnPrice),2);
                    }
                }
            }
           // printModel.ProductReturnBillDto.ReturnMoney

            return View(printModel);
            //return Content(" 这个是测试数据");
        }

        #endregion
    }

}
